package com.nikitova.craps3d.model {
	import com.carlcalderon.arthropod.Debug;
	import com.nikitova.craps3d.constants.AppData;
	import com.nikitova.craps3d.constants.Notifications;
	import com.nikitova.craps3d.model.vo.ConfigVO;
	import com.nikitova.utils.data.PathUtils;

	import org.puremvc.as3.multicore.utilities.startupmanager.interfaces.IStartupProxy;

	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	/**
	 * @author schranz
	 */
	public class ConfigProxy extends EntityProxy implements IStartupProxy 	{		public static const NAME		:String 	= 'ConfigProxy';		public static const SRNAME		:String 	= 'ConfigSRProxy';

		public function ConfigProxy()
		{			super(NAME);
					}		
		//**PUBLIC METHODS**//
		public function load():void
		{
			
			var xmlurl:String = PathUtils.formatURI(AppData.CONFIG_XML_URL, { v: Math.random().toString() } );
			var request:URLRequest = new URLRequest( xmlurl );
			var loader:URLLoader = new URLLoader();
			
			loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler, false, 0, true);
            loader.addEventListener(Event.COMPLETE, loaderCompleteHandler, false, 0, true);
			
			loader.load(request);
			
		}
		
		public function get gameConfigXmlPath():String
		{
			return configVO.gameConfigXml;
		}
		
		
		
		public function get xmlDir():String
		{
			return configVO.xmlDir;
		}
		
		public function get swfDir():String
		{
			return configVO.swfDir;
		}
		
		public function get daeDir():String
		{
			return configVO.daeDir;
		}
		
		public function get models():XMLList
		{
			return configVO.models;
		}
		
		//**PRIVATE METHODS**//
		private function loaderCompleteHandler( event:Event ):void 
		{
			var xml:XML;
			XML.ignoreWhitespace = true;
			try
			{
				xml = new XML( event.target.data );
			}
			catch (error:TypeError)
			{
				sendLoadedNotification( Notifications.CONFIG_LOAD_FAILED, NAME, SRNAME );
				return;
			}
			
			var vo:ConfigVO = new ConfigVO();
			
			vo.xmlDir				= xml.xml_dir;
			vo.gameConfigXml        = xml.gameConfig_xml;
			vo.swfDir				= xml.swf_dir;
			vo.daeDir				= xml.dae_dir;
			vo.models				= XMLList(xml.models.model);

			data = vo;
			
			sendNotification( Notifications.INIT_CONFIG );
			sendLoadedNotification( Notifications.CONFIG_LOADED, NAME, SRNAME );
		}
		
		private function errorHandler( event:IOErrorEvent ):void 
		{
			sendLoadedNotification( Notifications.CONFIG_LOAD_FAILED, NAME, SRNAME );
		}

		private function get configVO():ConfigVO
		{
			return ConfigVO(data);
		}
	}}